package com.haoxuer.discover.oauth.impl;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.haoxuer.discover.oauth.api.OauthHandler;
import com.haoxuer.discover.oauth.domain.TokenResponse;
import com.haoxuer.discover.oauth.domain.UserQQ;
import jodd.http.HttpRequest;

import java.io.IOException;

/**
 * Created by ada on 2017/6/29.
 */
public class QqOauthHandler implements OauthHandler {

  private String oauth_consumer_key;

  @Override
  public void setKey(String oauth_consumer_key) {
    this.oauth_consumer_key = oauth_consumer_key;
  }

  @Override
  public void setSecret(String secret) {

  }

  public UserQQ login(String accessToken, String openid) {
    HttpRequest request = HttpRequest.get("https://graph.qq.com/user/get_user_info");
    request.query("oauth_consumer_key", oauth_consumer_key);
    request.query("access_token", accessToken);
    request.query("openid", openid);
    request.query("format", "json");
    String body = "";
    try {
      body = request.send().body();
    } catch (Exception e) {
      e.printStackTrace();
    }

    JsonParser parser = new JsonParser();
    JsonElement e = parser.parse(body);
    if (e.getAsJsonObject().get("ret").getAsInt() != 0) {
      return null;
    }

    Gson gson = new Gson();
    UserQQ qq = gson.fromJson(body, UserQQ.class);
    if (qq != null && qq.getRet() != null && qq.getRet() == 0) {
      qq.setOpenid(openid);
    }
    return qq;

  }

  @Override
  public TokenResponse getToken(String code) {
    return null;
  }
}
